package icegps.com.pingdj.data.analysis;


/**
 * Created by 111 on 2018/1/9.
 */

public class AnalysisAsc {
    private String dataStr = "";
    private boolean isAdd;

    public boolean isAdd() {
        return isAdd;
    }

    public void analysisData(byte bt) {
        if (bt == '$') {
            isAdd = true;
        }
        if (isAdd && dataStr.length() >= 7 && bt == '\n') {
            dataStr = dataStr.trim();
            if (checksum(dataStr)) {
                if (onAscDataListener != null) {
                    onAscDataListener.onData(dataStr);
                }
            }
            dataStr = "";
            isAdd = false;
        }
        if (isAdd) {
            dataStr += new String(new byte[]{bt});
        }
        if (dataStr.length() >= 7) {
            if (!dataStr.startsWith("$ICEGPS")) {
                dataStr = "";
                isAdd = false;
            }
        }
        if (dataStr.length() > 256 * 2) {
            dataStr = "";
            isAdd = false;
        }
    }

    /**
     * 检查指令结尾校验和
     */
    private synchronized boolean checksum(String buff) {
        if (!buff.startsWith("$ICEGPS,")) return false;
        int sum = 0;
        int cs = 0;
        int pos = buff.indexOf("*");

        if (pos == -1)
            return false;
        for (int i = 1; i < pos; i++)
            sum ^= buff.charAt(i);
        try {
            cs = Integer.parseInt(buff.substring(pos + 1, buff.length()), 16);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            isAdd = false;
            dataStr = "";
        }
        return cs == sum;
    }

    OnAscDataListener onAscDataListener;

    public interface OnAscDataListener {
        void onData(String data);
    }

    public void setOnAscDataListener(OnAscDataListener onAscDataListener) {
        this.onAscDataListener = onAscDataListener;
    }

}
